import React, { useEffect, useState } from 'react';
import { Table, Divider, Modal, Form, Input, Select, Switch, Row, Col, Button, message } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RenderButtom from '@/components/RenderButton';
import MenuTree from '@/components/MenuTree';
import SearchBox from '@/components/SearchBox'
import {
  fetchOperationList,
  saveOrUpdateOperation,
  deleteOperation,
  getOneOperate,
} from '@/services/merchants';
import { connect } from 'dva';
import { formItemLayout } from '@/utils/utils'

const { confirm } = Modal;
const { Option } = Select;
const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))

const columns = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
  },
  {
    title: '功能描述',
    dataIndex: 'describes',
    key: 'describes',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    render: text => <span>{text == 0 ? '启用' : '停用'}</span>
  },
];

const OperateList = props => {
  const { getFieldDecorator } = props.form;
  const { inform } = props.role;
  const [data, setColData] = useState([]);
  const [record, setRecord] = useState([])
  const [btnType, setBtnType] = useState('')
  // 分配\新增角色模态框
  const [isShow, setState] = useState(false);

  useEffect(() => {
    getList();
  }, []);

  // 列表
  const getList = async params => {
    const r = await fetchOperationList(params);
    setColData(r.data);
  };

  // 新增修改角色
  const handleRole = async params => {
    const r = await saveOrUpdateRole(params);
    if (r.code == 0) getList();
  };

  // 查询
  const searchOneOperate = async params => {
    const r = await getOneOperate(params);
    setColData(r.data);
  };

  const removeRole = async record => {
    const res = await deleteOperation({
      id: record.id,
    });
    if (res.code == 0) {
      const index = data.findIndex(e => e.id == record.id);
      setColData(() => {
        data.splice(index, 1);
        return [...data];
      });
    }
  };

  // 新增/编辑 模态框
  const handleStatus = record => {
    setState(!isShow);
    props.dispatch({
      type: 'role/changeModelState',
      payload: {
        inform: record,
      },
    });
  };

  // 表单提交
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        const params = {
          ...inform,
          ...values,
          status: !!values.status ? 0 : 1,
          code: values.code ? values.code : Math.random(),
        }
        btnType != 1 && Object.assign(params, {id: values.id ? values.id : inform.id})
        saveOrUpdateOperation(params).then(() => {
          getList()
          setState(!isShow);
        });
      }
    });
  };

  // 查询表单
  const getFields = () => {
    return (
      <Col span={8}>
        <Form.Item label={`名称`}>
          {getFieldDecorator(`id`, {})
          (<Select
            showSearch
            filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
          >
            {data && data.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
          </Select>)}
        </Form.Item>
      </Col>
    );
  };
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      console.log('Received values of form: ', values);
      searchOneOperate({
        ...values,
      });
    });
  };

  // 清空查询条件
  const handleReset = () => {
    props.form.resetFields();
    getList()
  };

  // 按钮逻辑
  const handleBtn = type => {
    setBtnType(type)
    if (record.length != 1 && type != 1) return message.warning('请选择一个页面元素！');
    switch (type) {
      // 新增
      case 1:    
        return handleStatus();
      case 3:      
        return handleStatus(record[0]);
      // 查询
      case 2:      
        return handleSearch();
      // 删除
      case 4:
        return removeRole(record[0])
      default:
        break;
    }
  };

  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
    },
  };
  return (
    <PageHeaderWrapper>
      {/* 查询条件 */}
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table columns={columns} dataSource={hasSearchBtn ? data : []} rowSelection={rowSelection} rowKey={record => record.id} />
      {/* 新增/修改 */}
      <Modal
        title="新增/修改"
        visible={isShow}
        onOk={handleSubmit.bind(this)}
        onCancel={handleStatus.bind(this)}
        destroyOnClose
      >
        <Form {...formItemLayout}>
          <Form.Item label="按钮名称">
            {getFieldDecorator('name', {
              initialValue: inform && inform.name,
              rules: [
                {
                  required: true,
                  message: '请输入角色名称',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="描述">
            {getFieldDecorator('describes', {
              initialValue: inform && inform.describes,
              rules: [
                {
                  required: false,
                  message: '请输入描述',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="状态">
            {getFieldDecorator('status', {
              initialValue: inform && !inform.status ? true : false,
              valuePropName: 'checked',
            })(<Switch />)}
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default connect(({ role, global }) => ({
  role,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(OperateList));
